package com.controller.system.agent;

import com.entity.system.AgentNew;
import com.entity.system.StaticRole;
import com.entity.system.UserInfo;
import com.service.system.agent.AgentService;
import com.service.system.region.RegionService;
import com.service.system.user.UserInfoService;
import com.util.Const;
import com.util.FileUtil;
import com.util.Image;
import com.util.LogUtil;
import net.sf.json.JSONObject;
import org.apache.axis.components.uuid.UUIDGenFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller()
@RequestMapping("/agent")
public class AgentController {

    @Autowired
    AgentService agentService;

    @Autowired
    RegionService regionService;

    @Autowired
    UserInfoService userInfoService;


    /**
     * 查询代理商列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/findAgentList", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> findAgentList(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        Map<String,Object> map2 = new HashMap<>();
        map.put("pageSize", request.getParameter("pageSize"));
        map.put("pageNum", request.getParameter("pageNum"));
        if(StringUtils.isNotEmpty(request.getParameter("startTime"))){
            map.put("startTime",request.getParameter("startTime"));
        }
        if(StringUtils.isNotEmpty(request.getParameter("endTime"))){
            map.put("endTime",request.getParameter("endTime"));
        }
        if(StringUtils.isNotEmpty(request.getParameter("phone"))){
            Map<String,Object> map1 = userInfoService.findUserByPhone(request.getParameter("phone"));
            System.out.println(map1.get("code"));
            if(null != map1.get("user")){
                map.put("userId",((UserInfo)map1.get("user")).getId()+"");
            }else {
                map2.put("code",Const.ERROR_CODE);
                map2.put("message","查询失败");
                return map2;
            }

        }

        //shiro管理的session
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        Map<String,Object> map1 = (Map<String, Object>) session.getAttribute(Const.SESSION_allmenuList);

        if(null == map1){
            map2.put("code",Const.ERROR_CODE);
            map2.put("message","查询失败");
            return map2;
        }else {
            StaticRole sr = (StaticRole) map1.get("staticRole");
            if(sr != null && sr.getRoleCode().equals("VERSION_NEW_ROLE_AGENT")){
                UserInfo user = (UserInfo) session.getAttribute(Const.SESSION_USER);
                //代理商信息
                AgentNew an = agentService.getAgentNewByUserId(user.getId());
                if(an != null) {
                    if(an.getAgentLevel() == 1){
                        map.put("countyCode", an.getCountyCode());
                    }else if(an.getAgentLevel() == 2){
                        map.put("cityCode", an.getCityCode());
                    }else if(an.getAgentLevel() == 3){
                        map.put("provinceCode", an.getProvinceCode());
                    }
                }else {
                    LogUtil.info("*************你不是代理商*******************");
                    map2.put("code",Const.ERROR_CODE);
                    map2.put("message","查询失败");
                    return map2;
                }
            }
        }

//        if (StringUtils.isNotEmpty(request.getParameter("provinceCode"))) {
//            map.put("provinceCode", request.getParameter("provinceCode"));
//        }
//        if (StringUtils.isNotEmpty(request.getParameter("cityCode"))) {
//            map.put("cityCode", request.getParameter("cityCode"));
//        }
//        if (StringUtils.isNotEmpty(request.getParameter("countyCode"))) {
//            map.put("countyCode", request.getParameter("countyCode"));
//        }
        return agentService.findAgentList(map);
    }

    /**
     * 查询所有省份
     *
     * @return
     */
    @RequestMapping(value = "/findAllProvince", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> findAllProvince() {
        return regionService.findAllProvince();
    }

    /**
     * 根据省份查询市
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/findCityByProvince", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> findCityByProvince(HttpServletRequest request) {
        String provinceId = request.getParameter("provinceId");
        return regionService.findCityByProvince(provinceId);
    }

    /**
     * 根据市查询区县
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/findAreaByCity", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> findAreaByCity(HttpServletRequest request) {
        String cityId = request.getParameter("cityId");
        return regionService.findAreaByCity(cityId);
    }

    /**
     * 查询代理商收益列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/findAgentIncomeList", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> findAgentIncomeList(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        Map<String,Object> map2 = new HashMap<>();
        map.put("pageSize", request.getParameter("pageSize"));
        map.put("pageNum", request.getParameter("pageNum"));
        if (StringUtils.isNotEmpty(request.getParameter("startTime"))) {
            map.put("startTime", request.getParameter("startTime"));
        }
        if (StringUtils.isNotEmpty(request.getParameter("endTime"))) {
            map.put("endTime", request.getParameter("endTime"));
        }

        map.put("phone", request.getParameter("phone"));

        //shiro管理的session
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        Map<String,Object> map1 = (Map<String, Object>) session.getAttribute(Const.SESSION_allmenuList);

        if(null == map1){
            map2.put("code",Const.ERROR_CODE);
            map2.put("message","查询失败");
            return map2;
        }else {
            //当前登录用户角色
            StaticRole sr = (StaticRole) map1.get("staticRole");
            if(sr != null && sr.getRoleCode().equals("VERSION_NEW_ROLE_AGENT")){
                UserInfo user = (UserInfo) session.getAttribute(Const.SESSION_USER);
                //代理商信息
                AgentNew an = agentService.getAgentNewByUserId(user.getId());
                if(an != null) {
                    if(an.getAgentLevel() == 1){
                        map.put("countyCode", an.getCountyCode());
                    }else if(an.getAgentLevel() == 2){
                        map.put("cityCode", an.getCityCode());
                    }else if(an.getAgentLevel() == 3){
                        map.put("provinceCode", an.getProvinceCode());
                    }
                }else {
                    LogUtil.info("*************你不是代理商*******************");
                    map2.put("code",Const.ERROR_CODE);
                    map2.put("message","查询失败");
                    return map2;
                }
            }
        }

        return agentService.findAgentIncomeList(map);
    }

    /**
     * 添加代理商
     * @param file1
     * @param file2
     * @param file3
     * @param request
     * @return
     */
    @RequestMapping(value = "/addAgent",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> addAgent(MultipartFile file1,MultipartFile file2,MultipartFile file3,HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        List<MultipartFile> multipartFiles = new ArrayList<>();
        multipartFiles.add(file1);
        multipartFiles.add(file2);
        multipartFiles.add(file3);
        ResourceBundle rs = ResourceBundle.getBundle("environment");
        List<String> list = new ArrayList<>();
        for(MultipartFile file : multipartFiles){
            if(!file.isEmpty()){
                String contentType = file.getContentType();
                String suffix = FileUtil.getContentTypeSuffix(contentType);
//                String url = rs.getString("base.resource.url")+"/image/"+new SimpleDateFormat("yyyy/MM/dd").format(new Date())+ UUID.randomUUID().toString().replaceAll("-","")+"."+suffix;
                String url = rs.getString("base.resource.url")+"/image/upload";
//                String url = "D:/image/"+UUID.randomUUID().toString().replaceAll("-","")+"."+suffix;
                LogUtil.info(url);
                try {
                    Image image = FileUtil.uploadBytesAndPostBinImage(file.getBytes(),suffix,url);
                    if(image != null){
                        list.add(image.getUrl());
                    }else {
                        map.put("code",Const.ERROR_CODE);
                        map.put("message","添加失败");
                        return map;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    map.put("code",Const.ERROR_CODE);
                    map.put("message","添加失败");
                    return map;
                }
            }
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//        String fPhone = request.getParameter("fphone"); //用户手机号码
        AgentNew agentNew = new AgentNew();
        agentNew.setUserId(Long.parseLong(request.getParameter("userId")));
        if(StringUtils.isNotEmpty(request.getParameter("provinceCode"))){
            agentNew.setProvinceCode(request.getParameter("provinceCode")); //省
        }
        if(StringUtils.isNotEmpty(request.getParameter("cityCode"))){
            agentNew.setCityCode(request.getParameter("cityCode")); //市
        }
        if(StringUtils.isNotEmpty(request.getParameter("countyCode"))){
            agentNew.setCountyCode(request.getParameter("countyCode")); //区
        }
        agentNew.setAgentLevel(Integer.parseInt(request.getParameter("agentLevel")));
        agentNew.setAgentName(request.getParameter("agentName")); //真实姓名
        agentNew.setIdentityCard(request.getParameter("identityCard")); //身份证
        agentNew.setParentPhone(request.getParameter("parentPhone")); //推荐人
        agentNew.setIncomeCoefficient(Double.parseDouble(request.getParameter("incomeCoefficient"))); //收益系数
        try {
            agentNew.setSigningDate(format.parse(request.getParameter("signingDate"))); //签约日期
            agentNew.setValidStartDate(format.parse(request.getParameter("validStartDate"))); //履约开始日期
            agentNew.setValidEndDate(format.parse(request.getParameter("validEndDate"))); //履约结束日期
        } catch (ParseException e) {
            e.printStackTrace();
        }
        agentNew.setOperatorName(request.getParameter("operatorName")); //经办人姓名
        //shiro管理的session
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        UserInfo user = (UserInfo) session.getAttribute(Const.SESSION_USER);
        agentNew.setOperatorId(user.getId()); //经办人ID
        agentNew.setContractNo(request.getParameter("contractNo")); //合同号
        agentNew.setCreateTime(new Date());
        map.put("photos",list);
        agentNew.setIdentityCardImage(JSONObject.fromObject(map).toString());
        return agentService.addAgent(agentNew);
    }

    /**
     * 查询收益详情
     * @param request
     * @return
     */
    @RequestMapping(value = "/findIncomeDetail",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> findIncomeDetail(HttpServletRequest request){
        String userId = request.getParameter("userId");
        String pageSize = request.getParameter("pageSize");
        String pageNum = request.getParameter("pageNum");
        String incomeType = request.getParameter("incomeType");
        return agentService.findIncomeDetail(userId,pageSize,pageNum,incomeType);
    }

    /**
     * 查询代理商排行
     * @param request
     * @return
     */
    @RequestMapping(value = "/findAgentRank",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> findAgentRank(HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> map2 = new HashMap<>();
        String type = request.getParameter("findType");
        String pageSize = request.getParameter("pageSize");
        String pageNum = request.getParameter("pageNum");
        map.put("type",type);
        map.put("pageSize",pageSize);
        map.put("pageNum",pageNum);
        //shiro管理的session
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        Map<String,Object> map1 = (Map<String, Object>) session.getAttribute(Const.SESSION_allmenuList);

        if(null == map1){
            map2.put("code",Const.ERROR_CODE);
            map2.put("message","查询失败");
            return map2;
        }else {
            //当前登录用户角色
            StaticRole sr = (StaticRole) map1.get("staticRole");
            if(sr != null && sr.getRoleCode().equals("VERSION_NEW_ROLE_AGENT")){
                UserInfo user = (UserInfo) session.getAttribute(Const.SESSION_USER);
                //代理商信息
                AgentNew an = agentService.getAgentNewByUserId(user.getId());
                if(an != null) {
                    map.put("an",an);
                    if(an.getAgentLevel() == 1){
                        map.put("countyCode", an.getCountyCode());
                    }else if(an.getAgentLevel() == 2){
                        map.put("cityCode", an.getCityCode());
                    }else if(an.getAgentLevel() == 3){
                        map.put("provinceCode", an.getProvinceCode());
                    }
                }else {
                    LogUtil.info("*************你不是代理商*******************");
                    map2.put("code",Const.ERROR_CODE);
                    map2.put("message","查询失败");
                    return map2;
                }
            }
        }

        return agentService.findAgentRank(map);
    }
}
